package com.lagou.consumer;

import com.lagou.dto.UserBuyProductMsg;
import com.lagou.entity.COrder;
import com.lagou.repository.COrderRepository;
import com.lagou.service.ProductService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author mcl
 * @date 2021/10/13 19:12
 * @description
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "quick_buy_product", consumerGroup = "order_consumer", consumeMode = ConsumeMode.ORDERLY, consumeThreadMax = 1)
public class QuickbuyConsumer implements RocketMQListener<UserBuyProductMsg> {
    @Autowired
    private COrderRepository cOrderRepository;
    @Autowired
    private ProductService productService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @SneakyThrows
    @Override
    public void onMessage(UserBuyProductMsg userBuyProductMsg) {
        log.info(userBuyProductMsg.toString());

        // 减少库存
        productService.decrementProductCount(userBuyProductMsg.getProductId());

        // TODO: 2021/10/14 这里消费不能有太高的延迟
//        Thread.sleep(1000);
        rocketMQTemplate.syncSend("order_create", MessageBuilder.withPayload(userBuyProductMsg).build());

        // 创建订单 注意密等
//        COrder order;
//
//        List<COrder> bySql = cOrderRepository.findBySql(userBuyProductMsg.getUserId(), userBuyProductMsg.getProductId());
//        if (bySql.size() > 0) {
//            order = bySql.get(0);
//        } else {
//            order = new COrder();
//            order.setUserId(userBuyProductMsg.getUserId());
//            order.setProductId(userBuyProductMsg.getProductId());
//            order.setStatus("Paying");
//            order.setCreateTime(new Date());
//            cOrderRepository.save(order);
//        }
//
//        // 支付超时消息
//        rocketMQTemplate.syncSend("orer_timeout", MessageBuilder.withPayload(order).build(),10L,4);
    }
}
